package com.tuanzi.loan.web.bean.receipt.product;

import com.tuanzi.loan.business.entity.receipt.product.ReceiptProductPrice;
import com.tuanzi.loan.business.service.receipt.product.ReceiptProductPriceService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.receipt.product.ReceiptProductPriceSearchRequest;
import com.tuanzi.loan.vo.response.receipt.product.ReceiptProductPriceSearchResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.RowEditEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import java.util.List;

import static com.google.common.base.Preconditions.checkArgument;

@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class ReceiptProductPriceListBean extends JSFListingBean<ReceiptProductPriceSearchRequest,ReceiptProductPriceSearchResponse>{

    @Autowired
    private ReceiptProductPriceService receiptProductPriceService;

    private List<ReceiptProductPriceSearchResponse> receiptProductPriceList;

    @PostConstruct
    private void init() {
        String productId = getParamFromRequest("id");
        checkArgument(StringUtils.isNotBlank(productId));
        $ = new ReceiptProductPriceSearchRequest();
        $.setProductId(Long.parseLong(productId));
        reloadPriceList();
    }

    private void reloadPriceList() {
        receiptProductPriceList = receiptProductPriceService.findAllVoByCondition($);
    }

    //编辑完点击提交的时候，如果通过了校验，就保存
    public void onRowEdit(RowEditEvent event) {
        ReceiptProductPriceSearchResponse editRow = (ReceiptProductPriceSearchResponse) event.getObject();
        validateBeforeUpdate(editRow);
        if (getFacesContext().getMessageList().size()>0) {
            FacesContext.getCurrentInstance().validationFailed();
            return;
        }
        receiptProductPriceService.saveOrUpdatePrice(editRow,$);
        reloadPriceList();
    }

    public void onRowCancel() {
        reloadPriceList();
    }

    public void onAddNew(Long productId) {
        reloadPriceList();
        ReceiptProductPriceSearchResponse newRow = new ReceiptProductPriceSearchResponse();
        if (receiptProductPriceList.size()==0) {
            //如果是第一条数据，则设置开始值为1
            newRow.setMinApply(1);
        }else{
            //如果不是第一条数据，则去最后一条数据的最大申请数+1
            newRow.setMinApply(receiptProductPriceList.get(receiptProductPriceList.size() - 1).getMaxApply()+1);
        }
        receiptProductPriceList.add(0,newRow);
    }

    public void onRowDelete(Long deleteId) {
        receiptProductPriceService.deletePrice(deleteId,$);
        reloadPriceList();
    }

    private void validateBeforeUpdate(ReceiptProductPriceSearchResponse productPrice) {
        if (productPrice.getUnitPrice() == null) {
            addErrorMessage("每申请单价不能为空,请确认!");
        }
        if (productPrice.getMinApply() == null) {
            addErrorMessage("最小申请数不能为空,请确认!");
        }
        if (productPrice.getMaxApply() == null) {
            addErrorMessage("最大申请数不能为空,请确认!");
        }
        if (getFacesContext().getMessageList().size() > 0) {
            return;
        }
        //校验最小申请数是否大于最大申请数
        if (productPrice.getMinApply() >= productPrice.getMaxApply()) {
            addErrorMessage("最小申请数不能大于等于最大申请数,请确认!");
            return;
        }
        //校验最小申请数和最大申请数的包含区间
        List<ReceiptProductPrice> productPriceList = receiptProductPriceService.findPriceByApplyRangeCoincide(productPrice);
        if (productPriceList.size() > 0) {
            StringBuilder stringBuilder=new StringBuilder("此区间[");
            stringBuilder.append(productPrice.getMinApply()).append(",").append(productPrice.getMaxApply());
            stringBuilder.append("]和现有区间存在重叠,冲突区间如下:");
            productPriceList.forEach(price ->{
                stringBuilder.append("[").append(price.getMinApply()).append(",");
                stringBuilder.append(price.getMaxApply()).append("]");
                stringBuilder.append(",");
            } );
            stringBuilder.append("请确认!");
            addErrorMessage(stringBuilder.toString());
        }
    }
}
